package generics;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

class CollectionTypeGuesser {
	
    static Set<Class<?>> supers(Class<?> c){
        if (c == null) return new HashSet<Class<?>>();

        Set<Class<?>> s = supers(c.getSuperclass());
        s.add(c);
        return s;
    }

    static Class<?> lowestCommonSuper(Class<?> a, Class<?> b){
        Set<Class<?>> aSupers = supers(a);
        while (!aSupers.contains(b)){
            b = b.getSuperclass();
        }
        return b;
    }

    static Class<?> guessElementType(Collection<?> collection){
        Class<?> guess = null;
        for (Object o : collection){
            if (o != null){
                if (guess == null){
                    guess = o.getClass();
                }
                else if (guess != o.getClass()){
                    guess = lowestCommonSuper(guess, o.getClass());
                }
            }
        }
        return guess;
    }
}
